package org.zlex.chapter03;

import javax.crypto.*;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author : wushikai
 * <p>
 * date : 2021-04-22
 *
 * javax.crypto.Cipher 是 Java 加密扩展包 Java Cryptography Extension 的核心;
 *
 */
public class CipherDemo {


    /**
     *
     * 没有 cipher  就无法加密解密;
     * 使用 cipher  进行密钥的包装和解包装操作;
     *
     * */
    public  static void test ( ) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {


        String input = "草泥马";

        String des = "DES";

        KeyGenerator keyGenerator = KeyGenerator.getInstance( des  );


        SecretKey secretKey = keyGenerator.generateKey();
        Cipher cipher = Cipher.getInstance(des);


        cipher.init(Cipher.WRAP_MODE, secretKey);


        byte[] wrap = cipher.wrap(secretKey);

        String s = Base64.getEncoder().encodeToString(wrap);  // 为什么要包装密钥, 因为密钥对象很难存储, 直接包装出来 用Base64 编码为字符串直接存在db里面;

        System.out.println("base64 encoded warpSecretKey  =>  " + s );


       cipher.init(  Cipher.UNWRAP_MODE , secretKey);





        Key unwrap = cipher.unwrap(Base64.getDecoder().decode(s), des, Cipher.SECRET_KEY);   //接包装的 密钥

        cipher.init( Cipher.ENCRYPT_MODE, unwrap);

        byte[] encode = cipher.doFinal(input.getBytes());


        cipher.init( Cipher.DECRYPT_MODE, unwrap);


        byte[] decode = cipher.doFinal(encode);

        System.out.println(new String(decode));


    }


    public static void main(String[] args) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {


        test();

    }


}
